package com.wen.yygh.user.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wen.yygh.common.exception.YyghException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wen.yygh.common.helper.JwtHelper;
import com.wen.yygh.common.result.ResultCodeEnum;
import com.wen.yygh.common.utils.RedisUtil;
import com.wen.yygh.enums.AuthStatusEnum;
import com.wen.yygh.model.user.Patient;
import com.wen.yygh.model.user.UserInfo;
import com.wen.yygh.user.mapper.UserMapper;
import com.wen.yygh.user.service.PatientService;
import com.wen.yygh.user.service.UserService;
import com.wen.yygh.vo.user.LoginVo;
import com.wen.yygh.vo.user.UserAuthVo;
import com.wen.yygh.vo.user.UserInfoQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Wenjl
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserInfo> implements UserService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private PatientService patientService;

    /**
     * 用户登录
     *
     * @param loginVo
     * @return
     */
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        log.info("loginVo=>" + loginVo);
        //获取手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        //判断手机号和验证码是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        redisUtil.set("1", "1");
        log.info("redisUtil.get(phone)=>" + redisUtil.get(phone));
        // 比较手机验证吗
        if (!code.equals((redisUtil.get(phone)))) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }


        //判断是否是第一次登陆根据手机号查询数据库如果数据库中不存在则是第一次登录
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", phone);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        if (userInfo == null) {
            //添加信息到数据库
            userInfo = new UserInfo();
            userInfo.setName("");
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            baseMapper.insert(userInfo);
        }
        //判断账号是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //不是第一次则直接登录返回用户名和token
        Map<String, Object> result = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {

            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {

            name = userInfo.getPhone();
        }

        result.put("name", name);

        //jwt生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        result.put("token", token);

        return result;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置用户姓名
        userInfo.setName(userAuthVo.getName());
        //设置一些其他参数
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //更新user信息
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //UserInfoQueryVo 获取条件值
        //用户名称
        String name = userInfoQueryVo.getKeyword();
        //用户状态
        Integer status = userInfoQueryVo.getStatus();
        //认证状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        //开始时间
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        //结束时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();

        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }
        if (!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status", authStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            //大于等于创建时间
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            //小于等于创建时间
            wrapper.le("create_time", createTimeEnd);
        }
        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值
        userInfoPage.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });


        return userInfoPage;
    }

    @Override
    public void lock(Long id, Integer status) {

        //判断前端传过来的值是否符合规则
        if (status.intValue() == 0 || status.intValue() == 1) {
            //按照id查找用户
            UserInfo userInfo = baseMapper.selectById(id);
            userInfo.setStatus(status);
            //调用方法执行操作

            baseMapper.updateById(userInfo);
        }


    }

    @Override
    public Map<String, Object> show(Long id) {
        Map<String, Object> map = new HashMap<>();
        UserInfo userInfo = baseMapper.selectById(id);
        map.put("userInfo", userInfo);
        List<Patient> patientList = patientService.findAllByUserId(id);
        map.put("patientList", patientList);

        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        //2是通过认证，-1是未通过认证
        if (authStatus == 2 || authStatus == -1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    /**
     * 封装对象信息
     *
     * @param item
     */
    private void packageUserInfo(UserInfo item) {
        //处理认证状态编码
        item.getParam().put("authStatusStr", AuthStatusEnum.getStatusNameByStatus(item.getAuthStatus()));
        //处理用户状态编码
        String statusStr = item.getStatus() == 0 ? "锁定" : "正常";
        item.getParam().put("statusStr", statusStr);
    }
}
